package io.kiki.sba.registry.server.shared.client.manager;

import io.kiki.sba.registry.common.model.metaserver.ClientManagerAddress;
import io.kiki.sba.registry.common.model.metaserver.ClientManagerAddress.AddressVersion;
import io.kiki.sba.registry.common.model.metaserver.ClientManagerResult;
import io.kiki.sba.registry.store.api.DBResponse;
import io.kiki.sba.registry.store.api.meta.ClientManagerAddressRepository;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@Setter
@Getter
public class BaseClientManagerService implements ClientManagerService {

    @Autowired
    ClientManagerAddressRepository clientManagerAddressRepository;


    @Override
    public ClientManagerResult clientOpen(Set<String> ipSet) {
        Set<AddressVersion> addressSet = buildDefaultAddressVersions(ipSet);
        if (CollectionUtils.isEmpty(addressSet)) {
            return ClientManagerResult.buildFailRet();
        }
        return clientManagerAddressRepository.clientOpen(addressSet);
    }


    @Override
    public ClientManagerResult clientOff(Set<String> ipSet) {
        Set<AddressVersion> addressSet = buildDefaultAddressVersions(ipSet);
        if (CollectionUtils.isEmpty(addressSet)) {
            return ClientManagerResult.buildFailRet();
        }
        return clientManagerAddressRepository.clientOff(addressSet);
    }

    private Set buildDefaultAddressVersions(Set<String> ipSet) {
        if (CollectionUtils.isEmpty(ipSet)) {
            return Collections.EMPTY_SET;
        }
        Set<AddressVersion> addressSet = new HashSet<>(ipSet.size());
        for (String ip : ipSet) {
            addressSet.add(new AddressVersion(ip, true));
        }
        return addressSet;
    }

    @Override
    public ClientManagerResult clientOffWithSub(Set<AddressVersion> address) {
        return clientManagerAddressRepository.clientOff(address);
    }

    @Override
    public DBResponse queryClientOffAddress() {
        ClientManagerAddress clientManagerAddress = clientManagerAddressRepository.queryClientOffData();
        if (clientManagerAddress.getVersion() == 0) {
            return DBResponse.notfound().build();
        }
        return DBResponse.ok(clientManagerAddress).build();
    }

    @Override
    public ClientManagerResult reduce(Set<String> ipSet) {
        Set addressSet = buildDefaultAddressVersions(ipSet);
        if (CollectionUtils.isEmpty(addressSet)) {
            return ClientManagerResult.buildFailRet();
        }
        return clientManagerAddressRepository.reduce(addressSet);
    }

    @Override
    public void waitSynced() {
        clientManagerAddressRepository.waitSynced();
    }


}
